package cz.muni.fi.pb138.db;

import java.io.File;

import org.exist.xmldb.XmldbURI;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Database;
import org.xmldb.api.modules.CollectionManagementService;
import org.xmldb.api.modules.XMLResource;

/**
 *
 * @author Petra
 */

public class PutXml {

   public final static String URI = "xmldb:exist://localhost:8080/exist/xmlrpc";
   
	protected static void usage() {
		System.out.println("usage: org.exist.examples.xmldb.Put collection docName");
		System.exit(0);
	}

	public static int putXml(File file) throws Exception {

                String collection = "/db/biographies/";

        // inicializace driveru
		String driver = "org.exist.xmldb.DatabaseImpl";
		Class<?> cl = Class.forName(driver);			
		Database database = (Database)cl.newInstance();
		database.setProperty("create-database", "true");
		DatabaseManager.registerDatabase(database);
		
        // ziskani kolekce
		Collection col = 
			DatabaseManager.getCollection(URI + collection);
		if(col == null) {
            
            Collection root = DatabaseManager.getCollection(URI + XmldbURI.ROOT_COLLECTION);
            CollectionManagementService mgtService = 
                (CollectionManagementService)root.getService("CollectionManagementService", "1.0");
            col = mgtService.createCollection(collection.substring((XmldbURI.ROOT_COLLECTION + "/").length()));
        }
        // vytvoreni nového XMLResource
		XMLResource document = (XMLResource)col.createResource(file.getName(), "XMLResource");
		document.setContent(file);
		System.out.print("storing document " + document.getId() + "...");
		col.storeResource(document);
		System.out.println("ok.");
        //odstranenie suboru
        file.delete();
        return 0;
	}
}